package com.oa.car.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.car.entity.CarDriver;
import com.oa.car.service.CarDriverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月7日
 */
@RestController
@RequestMapping(value = "/*/oa/car/carDriver")
@Api(tags = {"司机表-操作接口"})
public class CarDriverController {

    static Logger logger = LoggerFactory.getLogger(CarDriverController.class);

    @Autowired
    private CarDriverService carDriverService;

    @ApiOperation(value = "司机表-查询列表", notes = " ")
    @ApiEntityParams(CarDriver.class)
    @ApiResponses({@ApiResponse(code = 200, response = CarDriver.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listCarDriver(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        //获取登录的机构号
        String branchId = LoginUtils.getCurrentUserInfo().getBranchId();
        params.put("branchId", branchId);
        RequestUtils.transformArray(params, "driverIds");
        QueryWrapper<CarDriver> qw = QueryTools.initQueryWrapper(CarDriver.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = carDriverService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    /*
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    @ApiOperation(value = "司机表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = CarDriver.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addCarDriver(@RequestBody CarDriver carDriver) {
        //简单校验手机号
        if (carDriver.getDriverPhoneno().length() != 11 || !isInteger(carDriver.getDriverPhoneno())) {
            return Result.error("手机号输入错误");
        }
        //简单校验邮箱
        if (!carDriver.getDriverEmel().contains("@")) {
            return Result.error("邮箱输入错误");
        }
        if (!StringUtils.isEmpty(carDriver.getCreateTime())) {
            carDriver.setCreateTime(new Date());
        }
        //判断司机机构号是否为空
        if (StringUtils.isEmpty(carDriver.getDriverBranchId())) {
            User user = LoginUtils.getCurrentUserInfo();
            carDriver.setDriverBranchId(user.getBranchId());
        }
        if (StringUtils.isEmpty(carDriver.getDriverBranchId())) {
            //获取登录的机构号
            String branchId = LoginUtils.getCurrentUserInfo().getBranchId();
            carDriver.setDriverBranchId(branchId);
        }
        if (StringUtils.isEmpty(carDriver.getDriverId())) {
            carDriver.setDriverId(carDriverService.createKey("driverId"));
        } else {
            CarDriver carDriverQuery = new CarDriver(carDriver.getDriverId());
            if (carDriverService.countByWhere(carDriverQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        carDriverService.save(carDriver);
        return Result.ok("add-ok", "添加成功！");
    }

    @ApiOperation(value = "司机表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delCarDriver(@RequestBody CarDriver carDriver) {
        if (StringUtils.isEmpty(carDriver.getDriverId())) {
            return Result.error("主键不能为空");
        }
        carDriverService.removeById(carDriver);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "司机表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = CarDriver.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editCarDriver(@RequestBody CarDriver carDriver) {
        if (StringUtils.isEmpty(carDriver.getDriverId())) {
            return Result.error("主键不能为空");
        }
        //简单校验手机号
        if (carDriver.getDriverPhoneno().length() != 11 || !isInteger(carDriver.getDriverPhoneno())) {
            return Result.error("手机号输入错误");
        }
        //简单校验邮箱
        if (!carDriver.getDriverEmel().contains("@")) {
            return Result.error("邮箱输入错误");
        }
        //判断司机机构号是否为空，为空则自动赋值
        if (StringUtils.isEmpty(carDriver.getDriverBranchId())) {
            User user = LoginUtils.getCurrentUserInfo();
            carDriver.setDriverBranchId(user.getBranchId());
        }
        carDriverService.updateById(carDriver);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ApiOperation(value = "司机表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = CarDriver.class, props = {}, remark = "司机表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = CarDriver.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        carDriverService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "司机表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelCarDriver(@RequestBody List<CarDriver> carDrivers) {
        User user = LoginUtils.getCurrentUserInfo();
        if (carDrivers.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<CarDriver> datasDb = carDriverService.listByIds(carDrivers.stream().map(i -> i.getDriverId()).collect(Collectors.toList()));

        List<CarDriver> can = new ArrayList<>();
        List<CarDriver> no = new ArrayList<>();
        for (CarDriver data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            carDriverService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getDriverId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "司机表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = CarDriver.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(CarDriver carDriver) {
        CarDriver data = (CarDriver) carDriverService.getById(carDriver);
        return Result.ok().setData(data);
    }

}
